import 'dart:convert';

import 'package:flutterhello/api/api.dart';
import 'package:flutterhello/pages/chat_detail/chat_detail.dart';
import 'package:flutterhello/pages/login/login.dart';
import 'package:flutterhello/util/host_util.dart';
import 'package:flutterhello/util/sort_util.dart';
import 'package:flutterhello/util/time_util.dart';
import 'package:flutterhello/util/web_socket_util.dart';
import 'package:flutterhello/widgets/my_toast.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert' as convert;
import 'package:date_format/date_format.dart';

class Controller extends GetxController {
  var count = 0.obs;
  increment() => count++;

  Controller get to => Get.find();

  // 底部导航tab选中
  var selectedIndex = 0.obs;
  // 导航切换
  void onItemTapped(int index) {
    selectedIndex.value = index;
  }

  // 数据存储
  SharedPreferences prefs;

  // 用户的基本信息
  var username = '';
  var token = '';
  var password = '';
  var userInfo = null;
  var allGroup = [];
  var myCreateGroup = [];
  var myJoinGroup = [];
  var myCreateAct = [];
  var myJoinAct = [];

  @override
  void onInit() async {
    // TODO: implement onInit
    super.onInit();
    await openApp();
  }

  // 打开app
  openApp() async {
    prefs = await SharedPreferences.getInstance();
    var user = await prefs.getString("userInfo");
    var tokenStr = await prefs.getString("token");
    if (user == '' || user == null) {
      Get.toNamed('/login_page');
    } else {
      userInfo = convert.jsonDecode(user);
      token = tokenStr;
      await getGroups();
      await readChatsHistory();
      connection();
    }
  }

  // 用户登录
  void userLogin() {
    var that = this;
    if (username != '' && password != '') {
      Api.login({'username': username, 'password': password}).then((res) async {
        if (res['code'] == 1000) {
          that.token = res['token'];
          var user = convert.jsonEncode(res['data']['user']);
          that.userInfo = res['data']['user'];
          await prefs.setString('token', token);
          await prefs.setString('userInfo', user);
          MyTost.showTost(res['message']);
          userInfo = convert.jsonDecode(user);
          await getGroups();
          await readChatsHistory();
          connection();
          Get.toNamed('/');
        } else {
          MyTost.showTost(res['message']);
        }
      });
    } else {
      MyTost.showTost('输入参数不完整');
    }
  }

  // 重新登录请求数据
  void loginRs() async {
    var that = this;
    await Api.login({
      'username': that.userInfo['username'],
      'password': that.userInfo['password']
    }).then((res) async {
      if (res['code'] == 1000) {
        that.token = res['token'];
        var user = convert.jsonEncode(res['data']['user']);
        that.userInfo = res['data']['user'];
        await prefs.setString('token', token);
        await prefs.setString('userInfo', user);
        MyTost.showTost(res['message']);
        userInfo = convert.jsonDecode(user);
        print(userInfo);
        await getGroups();
        await readChatsHistory();
        connection();
        Get.toNamed('/');
      } else {
        MyTost.showTost(res['message']);
      }
    });
  }

  // 用户退出
  void userLogout() async {
    await prefs.setString('token', "");
    await prefs.setString('userInfo', "");
    await prefs.setStringList('chats', []);
    userInfo = {};
    username = "";
    password = "";
    token = "";
    selectedIndex.value = 0;
    chatsMap = {};
    WebSocketUtility().closeSocket();
    Get.offAll(LoginPage());
  }

  // 获取groups
  void getGroups() async {
    myCreateGroup = [];
    myJoinGroup = [];
    var groupres = await Api.getUserGroups({"userID": userInfo['id']});
    if (groupres['code'] == 1000) {
      var groups = groupres['data']['groups'];
      allGroup = groups;
      groups.forEach((item) {
        if (item['createUser'] == userInfo['id']) {
          myCreateGroup.add(item);
        } else {
          myJoinGroup.add(item);
        }
      });
    }
    update();
  }

  // 获取activites
  void getActivites() async {
    myCreateAct = [];
    myJoinAct = [];
    var activiteres = await Api.getMyActivites({"userID": userInfo['id']});
    if (activiteres['code'] == 1000) {
      var activites = activiteres['data']['activite_list'];
      activites.forEach((item) {
        if (item['userID'] == userInfo['id']) {
          myCreateAct.add(item);
        } else {
          myJoinAct.add(item);
        }
      });
    }
    update();
  }

  var recruit_news = [];
  var activite_news = [];

  // 获取招募消息
  void getRecruitNews() async {
    var res = await Api.getRecruitNews();
    if (res['code'] == 1000) {
      this.recruit_news = res['data']['recruit_news_list'];
      update();
    }
  }

  // 获取活动消息
  void getActiviteNews() async {
    var res = await Api.getActiviteNews();
    if (res['code'] == 1000) {
      this.activite_news = res['data']['activite_news_list'];
      update();
    }
  }

  // 通知更新
  void myUpdata() {
    update();
  }

  List<String> chats = [];
  Map<String, List<dynamic>> chatsMap = {};

  // socket连接
  connection() async {
    print('----------socket连接-----------');
    WebSocketUtility().initWebSocket(
        onOpen: () {
          WebSocketUtility().initHeartBeat();
        },
        onMessage: getMessageListen,
        onError: (e) {
          print(e);
        },
        userID: this.userInfo['id']);
  }

  getMessageListen(msg) async {
    var msgJson = jsonDecode(msg);
    if (msgJson['module'] != null) {
    } else {
      if (msgJson['toID'] != null) {
        // 将消息保存
        await saveChat(jsonEncode(msgJson));
        // 将消息加载至chatMap
        if (chatsMap[msgJson['toID']] == null) {
          chatsMap[msgJson['toID']] = [];
        }
        chatsMap[msgJson['toID']].add(
          new MessageEntity(
            msg: msgJson['msg'],
            favicon: msgJson['user']['favicon'] != null
                ? msgJson['user']['favicon']
                : 'images/lyy.jpg',
            name: msgJson['user']['username'] != null
                ? msgJson['user']['username']
                : 'name',
            fromID: msgJson['fromID'],
            toID: msgJson['toID'],
            time: msgJson['time'] != null
                ? formatDate(
                    DateTime.fromMillisecondsSinceEpoch(msgJson['time']),
                    [yyyy, '-', mm, '-', dd, ' ', HH, ':', nn])
                : "",
          ),
        );
        chatsMap = SortUtil.chatMapSort(chatsMap);
        allGroup = SortUtil.groupSort(allGroup, chatsMap);
        update();
      }
    }
  }

  // 发送一条消息
  sendMsg(info, MessageEntity messageEntity) async {
    // chatsMap[info["id"]].add(messageEntity);
    // channel.sink.add();
    var nowTime = TimeUtil.getNowTime();
    String msgStr = jsonEncode({
      "fromID": messageEntity.fromID,
      "toID": messageEntity.toID,
      "msg": messageEntity.msg,
      "isGroup": messageEntity.isGroup,
      "time": nowTime
    });
    String saveMsgStr = jsonEncode({
      "own": messageEntity.own,
      "fromID": messageEntity.fromID,
      "toID": messageEntity.toID,
      "msg": messageEntity.msg,
      "isGroup": messageEntity.isGroup,
      "user": {"favicon": userInfo['favicon'], "username": "我"},
      "time": nowTime
    });
    if (chatsMap[info["id"]] == null) {
      chatsMap[info["id"]] = [];
    }
    messageEntity.favicon = userInfo['favicon'];
    messageEntity.name = "我";
    messageEntity.time = formatDate(
        DateTime.fromMillisecondsSinceEpoch(nowTime),
        [yyyy, '-', mm, '-', dd, ' ', HH, ':', nn]);
    chatsMap[info["id"]].add(messageEntity);
    chatsMap = SortUtil.chatMapSort(chatsMap);
    allGroup = SortUtil.groupSort(allGroup, chatsMap);
    WebSocketUtility().sendMessage(msgStr);
    saveChat(saveMsgStr);
    update();
  }

  // 保存消息
  saveChat(msg) async {
    var chatList = await prefs.getStringList('chats');
    if (chatList == null) {
      chatList = [];
    }
    chatList.add(msg);
    await prefs.setStringList('chats', chatList);
  }

  // 读取历史消息
  readChatsHistory() async {
    chats = await prefs.getStringList('chats');
    if (chats != null) {
      chats.forEach((element) {
        var msgJson = jsonDecode(element);
        print('-------------');
        print(msgJson['time']);
        if (chatsMap[msgJson['toID']] == null) {
          chatsMap[msgJson['toID']] = [];
        }
        chatsMap[msgJson['toID']].add(new MessageEntity(
            own: msgJson['own'] != null ? msgJson['own'] : false,
            msg: msgJson['msg'],
            favicon: msgJson['user'] != null
                ? msgJson['user']['favicon']
                : 'images/lyy.jpg',
            name:
                msgJson['user'] != null ? msgJson['user']['username'] : 'name',
            fromID: msgJson['fromID'],
            toID: msgJson['toID'],
            time: msgJson['time'] != null
                ? formatDate(
                    DateTime.fromMillisecondsSinceEpoch(msgJson['time']),
                    [yyyy, '-', mm, '-', dd, ' ', HH, ':', nn])
                : ""));
      });
    }
    chatsMap = SortUtil.chatMapSort(chatsMap);
    allGroup = SortUtil.groupSort(allGroup, chatsMap);
  }
}
